package com.iot08.api.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2021/5/11 15:47
 */
@Slf4j
public class FileUtil {

    public static MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

    /**
     * 获取音频长度
     *
     * @param file
     * @time: 2021/5/11 16:06
     * @author: Rock
     * @version 1.0
     */
    public static int getAmrDuration(File file) throws IOException {
        long duration = -1;
        int[] packedSize = {12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0};
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");
            long length = file.length();// 文件的长度
            int pos = 6;// 设置初始位置
            int frameCount = 0;// 初始帧数
            int packedPos = -1;

            byte[] datas = new byte[1];// 初始数据值
            while (pos <= length) {
                randomAccessFile.seek(pos);
                if (randomAccessFile.read(datas, 0, 1) != 1) {
                    duration = length > 0 ? ((length - 6) / 650) : 0;
                    break;
                }
                packedPos = (datas[0] >> 3) & 0x0F;
                pos += packedSize[packedPos] + 1;
                frameCount++;
            }
            duration += frameCount * 20;// 帧数*20
        } finally {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        }
        return (int) ((duration / 1000) + 1);
    }

    /**
     * @time: 2021/5/10 18:00
     * @author: Rock
     * @version 1.0
     */
    public static JSONObject getFileConfig() {
        try {
            ClassPathResource classPathResource = new ClassPathResource("wxgz.json");
            byte[] keywordsData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
            String jsonStr = new String(keywordsData, Charset.forName("utf-8"));
            return JSON.parseObject(jsonStr);
        } catch (Exception e) {
            log.error(" getFileConfig exception = "+e.getMessage(),e);
        }
        return null;
    }

    /**
     * @param pwd
     * @time: 2021/6/9 15:54
     * @author: Rock
     * @version 1.0
     */
    public static ByteArrayOutputStream getFileByte(String pwd) {
        ByteArrayOutputStream outputStream = null;
        try {
            File file = new File(pwd);
            if (file != null && file.isFile()) {
                InputStream inputStream = new FileInputStream(file);
                outputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
                inputStream.close();
            }
        } catch (Exception e) {
            log.error("getFileByte exception = {}. pwd = {}", e.getMessage(), pwd);
        }
        return outputStream;
    }

    public static boolean amrToMp3(File sourceFile, File targetFile){
        try {
//            File sourceFile = new File(source);
//            File targetFile = new File(target);

            //Audio Attributes
            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("libmp3lame");
            //比特率
            audio.setBitRate(12200);
//            audio.setBitRate(24400);
//            audio.setBitRate(128000);
            //设置通道值(1=单声道，2=立体声，4=四声道)
            audio.setChannels(1);
            //采样率
            audio.setSamplingRate(8000);

            //Encoding attributes
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setOutputFormat("mp3");
            attrs.setAudioAttributes(audio);

            //Encode
            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(sourceFile), targetFile, attrs);

            return true;
        } catch (Exception ex) {
            log.error("Arm To Mp3  转换异常:"+ex.getMessage(), ex);
            return false;
        }
    }

    public static void main(String[] args) {
//        amrToMp3("/Users/jianyou/Documents/赛诺/AmrToMp3_file/20240328messageCnO7qZ9Dwe51DY03amr.amr", "/Users/jianyou/Documents/赛诺/AmrToMp3_file/20240328messageCnO7qZ9Dwe51DY03mp3.mp3" );
    }

}
